package com.example.game1;

import java.util.Calendar;

import android.content.Context;

public class GameLoop implements Runnable
{
	/*
	 * Keeps the game loop from running too fast
	 * MIN_TIME_BETWEEN_ITERATIONS is in milliseconds
	 * 
	 * 1000 milliseconds / 60 FPS = 17ms/frame
	 * So a 17ms wait time will cap us at 60 FPS
	 */
	private static final int	MIN_TIME_BETWEEN_ITERATIONS	= 17;

	boolean						mKeepThreadRunning			= true;

	private static GameLoop		mInstance;

	private Thread				mGameThread;

	private MainActivity		mContext;

	private Object				mThreadLock;

	private GameLoop(MainActivity c) {

		mContext = c;
	}

	synchronized public static void init(MainActivity c)
	{

		// Guarantees that only one GridLoop can exist 
		if (mInstance == null)
			mInstance = new GameLoop(c);

	}

	synchronized public static GameLoop getInstance()
	{

		if (mInstance == null)
			throw new IllegalAccessError("GridManager not initialized!");

		return mInstance;
	}

	synchronized public void startGameLoop()
	{

		mThreadLock = new Object();
		mKeepThreadRunning = true;
		mGameThread = new Thread(this, "GameLoop");
		mGameThread.start();
	}

	synchronized public void stopGameLoop()
	{

		mKeepThreadRunning = false;
	}

	public void run()
	{

		long lastRun = 0;

		while (mKeepThreadRunning)
		{

			if (Calendar.getInstance().getTimeInMillis() - lastRun < MIN_TIME_BETWEEN_ITERATIONS)
			{
				// The thread is running too fast!
				synchronized (mThreadLock)
				{
					
					try
					{
						
						mThreadLock.wait(MIN_TIME_BETWEEN_ITERATIONS);
					} catch (InterruptedException e)
					{
						e.printStackTrace();
					}
				}
			}

			// Update the lastRun time with the current time
			lastRun = Calendar.getInstance().getTimeInMillis();

			//			updateCharacterPosition();
			mContext.mDrawingSurface.redraw();

		}

	}
}
